<template>
        <div class="addPosiIndex">
          <userHeader />
          <fixed />
          <div class="breadClum">
            <span>
                <router-link :to="{path:'/pageIndex'}" ><a class="bread1">当前位置：首页  >  </a></router-link>
               <router-link :to="{path:'/systemSetting'}" >  <a class="bread2">系统设置  ></a></router-link>
               <a class="bread2" >{{labelBread}}</a>
            </span>
          </div>
          <div class="e-form">
            <el-form ref="form" :model="form" label-width="106px" :rules="rules">
              <div class="e-form-top" v-if="!this.user_id">
                <el-form-item label="角色名称"  prop="role_names">
                  <el-input v-model="role_names" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述"  prop="role_desc">
                  <el-input v-model="form.role_desc" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="评价类型"  prop="appraise_type">
                  <el-select v-model="appraise_type" placeholder="请选择活动区域">
                    <el-option :label=item.name :value=item.id v-for="(item,index) in commentType" :key="index" >{{item.name}}</el-option>
                    <!--<el-option label="1" value="评级人员"></el-option>-->
                    <!--<el-option label="2" value="非评级人员"></el-option>-->
                  </el-select>
                </el-form-item>
                <el-form-item label="角色类型" prop="role_type">
                  <el-select v-model="role_type" placeholder="请选择活动区域">
                    <el-option :label=item.name :value=item.id v-for="(item,index) in roles_type" :key="index">{{item.name}}</el-option>
                    <!--<el-option label="总部" value="1"></el-option>-->
                    <!--<el-option label="分公司" value="2"></el-option>-->
                  </el-select>
                </el-form-item>

              </div>
              <div class="e-form-top" v-else>
                <el-form-item label="用户名称"  >
                  <el-input v-model="form.user_name" autocomplete="off" readonly=""></el-input>
                </el-form-item>
                <el-form-item label="真实姓名"  >
                  <el-input v-model="form.real_name" autocomplete="off" readonly=""></el-input>
                </el-form-item>
                <el-form-item label="用户角色"  prop="role_name" >
                  <el-input v-model="role_name" autocomplete="off" readonly=""></el-input>
                </el-form-item>
              </div>
              <div class="e-form-t" v-for="(item,index) in form.auth_parent" :key="index">
                <div class="e-form-t-check" >
                  <el-form-item >
                    <el-checkbox  v-model="item.checkAll" :label="item.name.auth_id"  @change="handleCheckAllChange(index,item)" >{{item.name.auth_name}}</el-checkbox>
                    <div class="e-checkbox-group" >
                      <el-checkbox-group v-model="item.check_auth_list"  @change="handleCheckedCitiesChange(item)">
                          <!-- <span>{{item.check_auth_list}}</span> -->
                        <div class="el-checkbox-group" >
                          <el-checkbox :label='item2.auth_id' v-for="(item2,index2) in item.auth_list"  :key="index2">{{item2.auth_name}}</el-checkbox>
                        </div>
                      </el-checkbox-group>
                    </div>
                  </el-form-item>
                </div>
              </div>
              <el-form-item class="el-form-btn">
                <!--<el-checkbox label="全选" name="type" v-model="form.checkAllAuth" @change="changeCheckAll"></el-checkbox>-->
                <el-button type="primary" @click="onSubmit('form')">确认</el-button>
                <el-button>取消</el-button>
              </el-form-item>
            </el-form>
          </div>

        </div>
      </template>

<script>
    import userHeader from '@/components/header.vue'
    import fixed from '@/components/fixed.vue'
    import {
        strToHexCharCode,
        toFixedBit,
        dec2hex,
        formatTime,
        getNewDate
    } from '@/utils/index.js'
    var mdSecret = 'fangyou968123456'
    export default {
        data() {
          var checkRole_names = (rule, value, callback) => {
            if (this.role_names == '' || this.role_names == undefined) {
//                    this.$alert('请输入角色名称', '提示')
              return callback(new Error('请输入角色名称'));
            } else {
              callback()
            }
          };
            var checkRole_name = (rule, value, callback) => {
                if (this.form.role_name == '' || this.form.role_name == undefined) {
//                    this.$alert('请输入角色名称', '提示')
                    return callback(new Error('请输入角色名称'));
                } else {
                    callback()
                }
            };
            var checkRole_desc = (rule, value, callback) => {
                if (this.form.role_desc == '' || this.form.role_desc == undefined) {
//                    this.$alert('请输入角色描述', '提示')
                    return callback(new Error('请输入角色描述'));
                } else {
                    callback()
                }
            };
            var checkAppraise = (rule, value, callback) => {
                if (this.appraise_type == '' || this.appraise_type == undefined) {
                    this.$alert('请选择评价类型', '提示')
                    return callback(new Error('请选择评价类型'));
                } else {
                    callback()
                }
            };
            var checkRole_type = (rule, value, callback) => {
                if (this.role_type == '' || this.role_type == undefined) {
                    this.$alert('请选择角色类型', '提示')
                    return callback(new Error('请选择角色类型'));
                } else {
                    callback()
                }
            };
            return {
              commentType:[
                {
                  id:1,
                  name:'评价人员'
                },
                {
                  id:2,
                  name:'非评价人员'
                }
              ],
              roles_type:[
                {
                  name:'集团',
                  id:1
                },{
                  name:'子公司',
                  id:2
                }
              ],
              role_names:'',
               role_type:'',
                role_name:'',
                roleList:[],
                checkAll: [],
                isIndeterminate: false,
                labelBread: '',
                selectAll: false,
                totalAuth: [],
                checkedCities: [],
                user_id:'',
                checkItem: [],
                appraise_type:"",
                form: {
                    auth_parent: [],
                    auth_list: [],
                  checkAllAuth: false,
                },
                rules: {
                  role_names: [{
                    required: true,
                    validator: checkRole_names,
                    trigger: 'blur'
                  }],
                    role_name: [{
                        required: true,
                        validator: checkRole_name,
                        trigger: 'blur'
                    }],
                    role_desc: [{
                        required: true,
                        validator: checkRole_desc,
                        trigger: 'blur'
                    }],
                    appraise_type: [{
                        required: true,
                        validator: checkAppraise,
                        trigger: 'blur'
                    }],
                    role_type: [{
                        required: true,
                        validator: checkRole_type,
                        trigger: 'blur'
                    }],
                }

            }
        },
        methods: {
            handleCheckAllChange(index, item) {
                //全选
                if (item['checkAll']) {
                    // item['check_auth_list'] = item['auth_list'];
                    item['auth_list'].forEach(el => {
                        item['check_auth_list'].push(el.auth_id)
                    })
                } else {
                    item['check_auth_list'] = [];
                }
            },
            handleCheckedCitiesChange(item) {
                //单选状态
                //当前 是否全选的状态 被子元素选择状态改变
                item.checkAll = item.check_auth_list.length === item.auth_list.length;
                item.isIndeterminate = item.check_auth_list.length > 0 && item.check_auth_list.length < item.auth_list.length;

            },
            onSubmit(formName) {
                //将权限列表的各项中被选中 项的id 出来 提交表单
              var authority_id = [],temp_auth_parent=[];
              console.log(this.form.auth_parent)
              this.form.auth_parent.forEach(element => {
                if(element.check_auth_list.length>0){
                  // console.log(element.name.company_id)
                  temp_auth_parent.push(element.name.auth_id);
                }
                authority_id = [...authority_id, ...element.check_auth_list]
              });
              authority_id = [...authority_id,...temp_auth_parent];
                console.log(authority_id)
                if (this.labelBread == '编辑角色') {
                  var appraise_type='';
                  var role_type='';
                  if(parseInt(this.appraise_type)){
                    appraise_type =this.appraise_type
                  }else if(this.appraise_type =='评价人员'){
                    appraise_type=1;
                  }else {
                    appraise_type=2;
                  };
                  if(parseInt(this.role_type)){
                    role_type=this.role_type;
                  }else  if(this.role_type =='集团'){
                    role_type=1
                  }else {
                    role_type=2
                  };
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.axios.put('/api/v1/system/role/' + this.role_id, {
                                    role_id: this.role_id,
                                    role_name: this.role_names, //角色名称
                                    role_desc: this.form.role_desc, //角色描述
                                    appraise_type: appraise_type, //评价类型（固定值1：评价人员 2：非评价人员
                                    role_type: role_type, //角色类型
                                    authority_id: authority_id //所要授权的权限id数组
                                })
                                .then((res) => {
                                    // console.log(res.data)
                                    // this.dialogFormVisible = false

                                    if (res.data.code == 0) {
                                        this.$alert('提交成功，点击确定返回上一层', '提示', {
                                            callback: action => {
                                                this.$router.go(-1)
                                            }
                                        })
                                    } else {

                                    }
                                }).catch((res) => {
                                    this.$alert(res.error, '提示')
                                })
                        } else {
                            // console.log('error submit!!');
                            return false;
                        }
                    })
                } else if (this.labelBread == '添加角色') {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            var data = {
                                    role_name: this.role_names,
                                    role_desc: this.form.role_desc,
                                    appraise_type: this.appraise_type,
                                    role_type: this.role_type,
                                    authority_id: authority_id
                                }
                                // console.log(data)
                            this.axios.post('/api/v1/system/role/', data)
                                .then((res) => {
                                    if (res.data.code == 0) {
                                      this.$alert('添加成功，点击确定返回上一层', '提示', {
                                        callback: action => {
                                          this.$router.go(-1)
                                        }
                                      })
                                    } else {
                                      this.$alert(res.data.message, '提示')
                                    }
                                })
                        } else {
                            // console.log('error submit!!');
                            return false;
                        }
                    })
                }else if(this.labelBread == '编辑用户权限'){
                  this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(authority_id);
                      this.axios.put('/api/v1/system/userauthority/' + this.user_id, {
                        authority_id: authority_id //所要授权的权限id数组
                      })
                        .then((res) => {

                          if (res.data.code == 0) {
                            this.$alert('提交成功，点击确定返回上一层', '提示', {
                              callback: action => {
                                this.$router.go(-1)
                              }
                            })
                          } else {

                          }
                        }).catch((res) => {
                        this.$alert(res.error, '提示')
                      })
                    } else {
                      // console.log('error submit!!');
                      return false;
                    }
                  })
                }
            },

            getAuthor() {
                //获取权限列表
//                return this.axios.get('/api/v1/system/authority')
                  return this.axios.get('/api/v1/system/access')

            },
            getEditor(id) {
                if(!this.$route.query.isManagement){
                  return this.axios.get('/api/v1/system/role/' + `${id}`)
                }else{
                  return this.axios.get('/api/v1/system/userauthority/' + `${id}`)
                }
            },
            getUser(id) {

            },
//          getRoleType(){
//                this.axios.get('/api/v1/system/role')
//                  .then((res)=>{
//                    if(res.data.code==0){
//                        this.roleList =res.data.data;
//                     }
//                  })
//          },
          changeCheckAll() {
            /*页面底部全选操作
             * 全选时，将每个顶级权限的权限设置为true
             * 再执行 顶级权限全选的操作（handleCheckAllChange）
             * */
            if (this.form.checkAllAuth) {
              this.form.auth_parent.forEach(el => {
                el.checkAll = true
              })
            } else {
              this.form.auth_parent.forEach(el => {
                el.checkAll = false
              })
            }
            this.form.auth_parent.forEach((el, index) => {
              this.handleCheckAllChange(index, el)
            })
          },

        },
        mounted() {
            if (this.$route.query.role_id >= 0) {
                if(this.$route.query.isManagement){
                  this.labelBread = '编辑用户权限';
                  this.user_id =this.$route.query.user_id;
                  this.form.user_name =this.$route.query.user_name;
                  this.form.real_name =this.$route.query.real_name;
                  this.role_name =this.$route.query.real_roal;
//                  console.log(this.form.role_name)
//                  /api/v1/system/userauthority/
//                  this.getRoleType();
                }else{
                  this.labelBread = '编辑角色';
//                  this.role_names =this.$route.query.real_name
                }
                this.role_id = this.$route.query.role_id;
                this.getAuthor().then(res => {
                    if (res.data.code == 0) {
                        this.totalAuth = res.data.data
                        for (var i in res.data.data) {
                            if (res.data.data[i].auth_pid == 0) {
                                this.form.auth_parent.push({
                                    name: res.data.data[i], //顶级权限类目
                                    auth_list: [], //顶级权限类目下的项目
                                    checkAll: false, //是否全选的标记
                                    isIndeterminate: true,
                                    check_auth_list: [], //被选的中的元素
                                })
                            }
                        }

                        for (var i in this.form.auth_parent) {
                            for (var j in this.totalAuth) {
                                if (this.form.auth_parent[i].name.auth_id == this.totalAuth[j].auth_pid) {
                                    this.form.auth_parent[i].auth_list.push(this.totalAuth[j])
                                }
                            }
                        }
                        // console.log(this.auth_parent)
                    } else {
                        this.$alert(res.data.message, '提示')
                    }

                }).then(res => {
                    /*=====================*/
                    var id='';
                    if(this.$route.query.isManagement){
                        id=this.$route.query.user_id
                    }else{
                        id=this.$route.query.role_id;
                    }
                        this.getEditor(id).then((res) => {
                          if (res.data.code == 0) {
                              console.log(res.data.data)
                            var data = res.data.data;
                            //添加除 角色权限列表 的其他数据  页面头部数据
                            this.form = Object.assign(this.form, res.data.data);
                            this.role_names = this.form.role_name;
                            if(this.form.appraise_type==1){
                              this.appraise_type ="评价人员"
                            }else {
                              this.appraise_type ="非评价人员"
                            };
                            if(this.form.role_type==1){
                              this.role_type ="集团"
                            }else{
                              this.role_type ="子公司"
                            }
                            //将用户权限列表 按顶级权限 整理
                            this.form.auth_parent.forEach((el, i) => {
                              data.authority_list.forEach(element => {
                                //将数据 加到 每一项的 checklist
                                // console.log(el.name.auth_id == element.auth_pid)
                                if (el.name.auth_id == element.auth_pid) {
                                  el.check_auth_list.unshift(element.auth_id);
                                }
                              })

                              el.checkAll = el.auth_list.length == el.check_auth_list.length ? true : false
                            })
                          } else {
                            this.$alert(res.data.message, '提示')
                          }
                        }).then((res)=>{
                          //当编辑权限时将全选初始为true
                          this.form.checkAllAuth = true;
                          this.form.auth_parent.forEach(el=>{
                            // console.log(el.checkAll)
                            if(!el.checkAll){
                              this.form.checkAllAuth = false
                            }
                          })
                        })
                          .catch((err) => {
                            this.$alert(err.message, '提示')
                          })


                })

            } else {
                this.labelBread = '添加角色';
                this.getAuthor().then((res) => {
                        if (res.data.code == 0) {
                            this.totalAuth = res.data.data
                            for (var i in res.data.data) {
                                if (res.data.data[i].auth_pid == 0) {
                                    this.form.auth_parent.push({
                                        name: res.data.data[i], //顶级权限类目
                                        auth_list: [], //顶级权限类目下的项目
                                        checkAll: false, //是否全选的标记
                                        isIndeterminate: true,
                                        check_auth_list: [], //被选的中的元素
                                    })
                                }
                            }
                            // console.log(this.auth_parent)
                        } else {
                            this.$alert(res.data.message, '提示')
                        }
                    }).then((res) => {
                        for (var i in this.form.auth_parent) {
                            for (var j in this.totalAuth) {
                                if (this.form.auth_parent[i].name.auth_id == this.totalAuth[j].auth_pid) {
                                    this.form.auth_parent[i].auth_list.push(this.totalAuth[j])
                                }
                            }
                        }


                    })
                    .catch((err) => {
                        this.$alert(err.message, '提示')
                    })
                    // console.log('确认编辑')

            }
        },
        components: {
            fixed,
            userHeader,
        },
    }
</script>
<style scoped>
    .addPosiIndex {
        width: 100%;
        height: 100%;
        background: #f1f1f1;
         padding: 10px;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
    }

    .addPosiIndex .el-form {
        background: white;
    }

    .addPosiIndex .el-form>>>.e-form-top {
        background: #f3f9ed;
        padding: 30px 0;
        margin-bottom: 10px;
    }

    .addPosiIndex .el-form>>>.e-form-t {
        background: #f3f9ed;
    }

    .addPosiIndex .el-form>>>.el-form-item__label {
        width: 106px;
        margin-left: 72px;
        text-align: right;
    }

    .addPosiIndex .el-form>>>.el-input {
        width: 378px;
        height: 38px;
        border-radius: 4px;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
    }

    .addPosiIndex .e-form {
        margin: 0 10px;
        padding: 10px 28px;
        background: white;
    }

    .addPosiIndex .el-form>>>.el-form-item {
        margin-bottom: 24px;
    }

    .addPosiIndex .el-form>>>.e-form-t .el-checkbox-group {
        padding-right: 300px;
        background: #e4f1d5;
        padding-left: 46px;
        margin-bottom: 20px;
        padding-top: 20px;
        padding-bottom: 20px;
    }

    .addPosiIndex .el-form>>>.e-form-t .el-checkbox {
        margin-left: 0;
        width: 300px;
    }

    .addPosiIndex .el-form>>>.el-checkbox__input.is-checked .el-checkbox__inner,
    .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background: #8bc34a;
        border-color: #8bc34a;
    }

    .addPosiIndex .el-form>>>.el-checkbox__input.is-checked+.el-checkbox__label {
        color: #333333;
    }

    .addPosiIndex .el-form>>>.el-checkbox__inner {
        width: 18px;
        height: 18px;
    }

    .addPosiIndex .el-form>>>.el-checkbox__label {
        font-size: 14px;
    }

    .addPosiIndex .el-form>>>.el-checkbox__inner::after {
        left: 6px;
        width: 4px;
        height: 10px;
    }

    .addPosiIndex .el-form>>>.el-form-item__error {
        left: 80px;
    }

    .addPosiIndex .el-form>>>.el-form-btn .el-form-item__content {
        text-align: center;
    }

    .addPosiIndex .el-form>>>.el-form-btn .el-form-item__content .el-button--primary {
        background: #8bc34a;
        color: white;
        font-size: 16px;
        border-color: #8bc34a;
    }

    .addPosiIndex .el-form>>>.el-form-btn .el-form-item__content .el-checkbox {
        margin-right: 47px;
    }

    .addPosiIndex .el-form>>>.el-form-btn .el-button {
        padding: 9px 24px;
    }

    .addPosiIndex .el-form>>>.e-checkbox-group {
        padding-right: 80px;
    }

    @media screen and (max-width: 1400px) {
        .addPosiIndex{
          padding: 6px;
        }
        .addPosiIndex .el-form>>>.e-form-t .el-checkbox {
            margin-left: 0;
            width: 240px;
        }
        .addPosiIndex .el-form>>>.e-checkbox-group {
            padding-right: 40px;
        }
        .addPosiIndex .el-form>>>.e-form-t .el-checkbox-group {
            padding-right: 0px;
        }
    }
</style>
